import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {map} from 'rxjs/operators';
import {Authenticator} from './authenticator';


@Injectable({providedIn: 'root'})
export class Authenticate {

  isLoggedIn = false;

  authenticator: Authenticator;

  // store the URL so we can redirect after logging in
  redirectUrl: string;

  constructor(private http: HttpClient) {
  }

  first(code: string): Observable<boolean> {
    return this.http
      .get(`/wx/index/${code}`)
      .pipe(
        map((res: any) => {
          this.authenticator = res;
          this.isLoggedIn = true;
          localStorage.setItem('authenticator', JSON.stringify(this.authenticator));
          return this.isLoggedIn;
        })
      );
  }

  byOpenid(id: string): Observable<boolean> {
    return this.http
      .get(`/wx/info/${id}`)
      .pipe(
        map((res: any) => {
          this.authenticator = res;
          this.isLoggedIn = true;
          localStorage.setItem('authenticator', JSON.stringify(this.authenticator));
          return this.isLoggedIn;
        })
      );
  }

  authentication(): Observable<boolean> {
    const authStr = localStorage.getItem('authenticator');
    if (authStr) {
      this.authenticator = JSON.parse(authStr);
      this.isLoggedIn = true;
      return of(this.authenticator != null);
    } else {
      return of(false);
    }
  }

  logout(): void {
    this.isLoggedIn = false;
    localStorage.removeItem('authenticator');
  }

}
